<?php

/**
 * Odb module
 *
 * @author coder_
 */

Class Odb extends _Module
{
    private static $instance;

    private $dependencies = array('Db');
    private $db;

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    public static function &getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self;
        }
        return self::$instance;
    }

    public function initialize()
    {
        $this->db = getModule('Db');
    }

    public function getDependencies()
    {
        return $this->dependencies;
    }

    private function Encode($data)
    {
        return json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
    }

    private function Decode($string)
    {
        return json_decode($string, true);
    }

    public function Save($data = null, $name = '')
    {
        if (is_null($data) || empty($name)) return false;

        $data = $this->Encode($data);
        $q = 'INSERT INTO `objects` (`Object`, `Name`, `Timestamp`)
              VALUES (:data, :name, UNIX_TIMESTAMP())
              ON DUPLICATE KEY UPDATE `OBJECT` = :data, `Timestamp` = UNIX_TIMESTAMP()';
        $this->db->exec($q, array('data' => $data, 'name' => $name));

        return true;

    }

    public function Load($name = '')
    {
        if ($name != '') {
            $q = 'SELECT `Object` FROM `objects` WHERE `Name` = ?';
            $result = $this->db->getSingle($q, array($name));
            if ($result) {
                return $this->Decode($result);
            } else {
                $this->errored = !$result;
                return null;
            }
        }

        return null;
    }
}